package com.dc.config;

import com.dc.pojo.User;
import com.dc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权==>doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//        info.addStringPermission("user:browse");

        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //拿到User对象实体（账户数据）
        User principal = (User) subject.getPrincipal();//因为认证方法传了账户数据才能拿到对象，否则空指针异常

        //根据设定给该用户授权和分配角色  授予不同权限不同角色可做不同的事
        String perms = principal.getPerms();
        String roles = principal.getRoles();

        info.addStringPermission(perms);
        info.addRole(roles);


/*
        Set<String> roles = new HashSet<>();
        roles.add(principal.getRoles());
        // 权限集合
        Set<String> permissions = new HashSet<>();
        permissions.add(principal.getPerms());

        // 封装角色权限信息集合
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        info.setRoles(roles);
        info.setStringPermissions(permissions);
*/

        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证==>doGetAuthenticationInfo");

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //连接数据库查询用户
        User user = userService.queryUserByName(token.getUsername());

        //如果没有这个用户
        if(user==null){
            return null;//抛出异常 UnknownAccountException
        }

        //shiro帮我们进行密码认证   并将账户数据丢给Subject
        System.out.println("shiro帮我们进行密码认证   并将账户数据丢给Subject");
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
